<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>MetasoCreator - 智能创作平台</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            overflow: hidden;
        }

        /* 主容器 - 使用Grid布局实现三大区域 */
        .main-container {
            display: grid;
            grid-template-areas: 
                "header header header"
                "main right-sidebar right-sidebar";
            grid-template-columns: 1fr 400px;
            grid-template-rows: 80px 1fr;
            height: 100vh;
            gap: 0;
            min-width: 1200px; /* 确保最小宽度 */
        }

        /* 1. 顶部导航栏区域 - 系统功能模块切换 */
        .header {
            grid-area: header;
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
            padding: 0 30px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            box-shadow: 0 2px 20px rgba(0,0,0,0.1);
            z-index: 1000;
        }

        .header-left {
            display: flex;
            align-items: center;
            gap: 20px;
        }

        .logo {
            font-size: 2em;
            font-weight: bold;
            text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
        }

        .nav-menu {
            display: flex;
            gap: 30px;
        }

        .nav-item {
            padding: 12px 24px;
            border-radius: 25px;
            cursor: pointer;
            transition: all 0.3s ease;
            font-weight: 500;
            border: 2px solid transparent;
        }

        .nav-item:hover {
            background: rgba(255,255,255,0.2);
            transform: translateY(-2px);
        }

        .nav-item.active {
            background: rgba(255,255,255,0.3);
            border-color: rgba(255,255,255,0.5);
            box-shadow: 0 4px 15px rgba(0,0,0,0.2);
        }

        .header-right {
            display: flex;
            align-items: center;
            gap: 20px;
        }

        .status-indicator {
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 14px;
        }

        .status-dot {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background: #4ade80;
            animation: pulse 2s infinite;
        }

        @keyframes pulse {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.5; }
        }

        /* 2. 左侧主应用区域 - 用户交互和内容展示 */
        .main-content {
            grid-area: main;
            background: #f8fafc;
            display: flex;
            flex-direction: column;
            overflow: hidden;
            min-width: 0; /* 防止内容溢出 */
            flex: 1; /* 确保占用可用空间 */
        }

        /* 2.1 功能说明区域 - 显示当前功能的说明 */
        .function-info {
            background: white;
            padding: 20px 30px;
            border-bottom: 1px solid #e2e8f0;
            text-align: center;
        }

        .function-title {
            font-size: 24px;
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 10px;
        }

        .function-description {
            color: #64748b;
            font-size: 16px;
            line-height: 1.5;
        }

        /* 2.1 参数配置区域 - 为每个功能提供参数选择界面 */
        .parameter-config {
            background: white;
            padding: 25px 30px;
            border-bottom: 1px solid #e2e8f0;
        }

        .config-title {
            font-size: 20px;
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .config-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 20px;
        }

        .config-item {
            display: flex;
            flex-direction: column;
        }

        .config-label {
            font-weight: 600;
            color: #374151;
            margin-bottom: 8px;
            font-size: 14px;
        }

        .config-input {
            padding: 10px 12px;
            border: 2px solid #e2e8f0;
            border-radius: 8px;
            font-size: 14px;
            transition: all 0.3s ease;
        }

        .config-input:focus {
            outline: none;
            border-color: #4facfe;
            box-shadow: 0 0 0 3px rgba(79, 172, 254, 0.1);
        }

        .config-select {
            padding: 10px 12px;
            border: 2px solid #e2e8f0;
            border-radius: 8px;
            font-size: 14px;
            background: white;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .config-select:focus {
            outline: none;
            border-color: #4facfe;
            box-shadow: 0 0 0 3px rgba(79, 172, 254, 0.1);
        }

        /* 自定义多选下拉框样式 */
        .custom-multiselect {
            position: relative;
            width: 100%;
        }

        .multiselect-input {
            width: 100%;
            min-height: 42px;
            padding: 8px 40px 8px 12px;
            border: 2px solid #e2e8f0;
            border-radius: 8px;
            background: white;
            cursor: pointer;
            display: flex;
            flex-wrap: wrap;
            align-items: center;
            gap: 6px;
            transition: all 0.3s ease;
        }

        .multiselect-input:hover {
            border-color: #cbd5e1;
        }

        .multiselect-input.focused {
            border-color: #4facfe;
            box-shadow: 0 0 0 3px rgba(79, 172, 254, 0.1);
        }

        .multiselect-arrow {
            position: absolute;
            right: 12px;
            top: 50%;
            transform: translateY(-50%);
            width: 0;
            height: 0;
            border-left: 5px solid transparent;
            border-right: 5px solid transparent;
            border-top: 5px solid #64748b;
            transition: transform 0.3s ease;
            pointer-events: none;
        }

        .multiselect-input.focused .multiselect-arrow {
            transform: translateY(-50%) rotate(180deg);
        }

        .multiselect-tag {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 500;
            display: flex;
            align-items: center;
            gap: 4px;
            max-width: 120px;
        }

        .multiselect-tag-text {
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }

        .multiselect-tag-remove {
            cursor: pointer;
            font-size: 14px;
            line-height: 1;
            opacity: 0.8;
            transition: opacity 0.2s ease;
        }

        .multiselect-tag-remove:hover {
            opacity: 1;
        }

        .multiselect-placeholder {
            color: #94a3b8;
            font-size: 14px;
            pointer-events: none;
        }

        .multiselect-dropdown {
            position: absolute;
            top: 100%;
            left: 0;
            right: 0;
            background: white;
            border: 2px solid #e2e8f0;
            border-top: none;
            border-radius: 0 0 8px 8px;
            max-height: 200px;
            overflow-y: auto;
            z-index: 1000;
            display: none;
        }

        .multiselect-dropdown.show {
            display: block;
        }

        .multiselect-option {
            padding: 10px 12px;
            cursor: pointer;
            transition: background-color 0.2s ease;
            border-bottom: 1px solid #f1f5f9;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .multiselect-option:last-child {
            border-bottom: none;
        }

        .multiselect-option:hover {
            background-color: #f8fafc;
        }

        .multiselect-option.selected {
            background-color: rgba(79, 172, 254, 0.1);
            color: #4facfe;
            font-weight: 500;
        }

        .multiselect-option-checkbox {
            width: 16px;
            height: 16px;
            border: 2px solid #e2e8f0;
            border-radius: 3px;
            position: relative;
            transition: all 0.2s ease;
        }

        .multiselect-option.selected .multiselect-option-checkbox {
            background: #4facfe;
            border-color: #4facfe;
        }

        .multiselect-option.selected .multiselect-option-checkbox::after {
            content: '✓';
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            color: white;
            font-size: 10px;
            font-weight: bold;
        }

        .config-checkbox-group {
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
            padding: 10px;
            border: 2px solid #e2e8f0;
            border-radius: 8px;
            background: #f8fafc;
        }

        .config-checkbox-item {
            display: flex;
            align-items: center;
            gap: 8px;
            cursor: pointer;
        }

        .config-checkbox-item input[type="checkbox"] {
            width: 16px;
            height: 16px;
            accent-color: #4facfe;
        }

        .config-checkbox-item label {
            font-size: 14px;
            color: #374151;
            cursor: pointer;
        }

        .config-radio-group {
            display: flex;
            gap: 20px;
            padding: 10px;
            border: 2px solid #e2e8f0;
            border-radius: 8px;
            background: #f8fafc;
        }

        .config-radio-item {
            display: flex;
            align-items: center;
            gap: 8px;
            cursor: pointer;
        }

        .config-radio-item input[type="radio"] {
            width: 16px;
            height: 16px;
            accent-color: #4facfe;
        }

        .config-radio-item label {
            font-size: 14px;
            color: #374151;
            cursor: pointer;
        }

        /* 配置区域样式 */
        .config-section {
            display: block;
        }

        .config-section.hidden {
            display: none;
        }

        /* 2.2 中间对话内容展示区域 */
        .chat-container {
            flex: 1;
            padding: 30px;
            overflow-y: auto;
            background: white;
            margin: 20px;
            border-radius: 20px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.08);
        }

        .chat-message {
            margin-bottom: 25px;
            display: flex;
            gap: 15px;
        }

        .message-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 18px;
            flex-shrink: 0;
        }

        .user-avatar {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
        }

        .assistant-avatar {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }

        .message-content {
            flex: 1;
            background: #f8fafc;
            padding: 20px;
            border-radius: 18px;
            border-top-left-radius: 5px;
            position: relative;
        }

        .assistant-message .message-content {
            background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
            border-top-left-radius: 18px;
            border-top-right-radius: 5px;
        }

        .message-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
            font-size: 14px;
            color: #64748b;
        }

        .message-text {
            line-height: 1.6;
            color: #334155;
        }

        .search-results {
            margin-top: 15px;
        }

        .search-result-item {
            background: white;
            padding: 15px;
            border-radius: 12px;
            margin-bottom: 10px;
            border: 1px solid #e2e8f0;
            transition: all 0.3s ease;
        }

        .search-result-item:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        }

        .result-title {
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 8px;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .result-url {
            color: #3b82f6;
            font-size: 14px;
            margin-bottom: 8px;
            word-break: break-all;
        }

        .result-snippet {
            color: #64748b;
            font-size: 14px;
            line-height: 1.5;
        }

        .result-meta {
            display: flex;
            gap: 15px;
            margin-top: 10px;
            font-size: 12px;
            color: #94a3b8;
        }

        /* 2.3 底部发送框区域 */
        .input-container {
            background: white;
            padding: 20px 30px;
            border-top: 1px solid #e2e8f0;
            display: flex;
            gap: 15px;
            align-items: flex-end;
        }

        .input-wrapper {
            flex: 1;
            position: relative;
        }

        .message-input {
            width: 100%;
            padding: 15px 20px;
            border: 2px solid #e2e8f0;
            border-radius: 25px;
            font-size: 16px;
            resize: none;
            transition: all 0.3s ease;
            font-family: inherit;
            line-height: 1.5;
        }

        .message-input:focus {
            outline: none;
            border-color: #4facfe;
            box-shadow: 0 0 0 3px rgba(79, 172, 254, 0.1);
        }

        .send-button {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
            border: none;
            padding: 15px 30px;
            border-radius: 25px;
            cursor: pointer;
            font-size: 16px;
            font-weight: 600;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .send-button:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(79, 172, 254, 0.4);
        }

        .send-button:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }

        /* 3. 右侧数据来源展示区域 - 展示系统检索到的实际数据来源 */
        .right-sidebar {
            grid-area: right-sidebar;
            background: white;
            border-left: 1px solid #e2e8f0;
            overflow-y: auto;
            padding: 20px;
            min-width: 400px; /* 确保最小宽度 */
            max-width: 400px; /* 限制最大宽度 */
        }

        .sidebar-section {
            margin-bottom: 30px;
        }

        .sidebar-title {
            font-size: 18px;
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 15px;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        /* 数据来源项目样式 */
        .data-source-item {
            background: #f8fafc;
            padding: 15px;
            border-radius: 12px;
            margin-bottom: 10px;
            border: 1px solid #e2e8f0;
            transition: all 0.3s ease;
        }

        .data-source-item:hover {
            background: #f1f5f9;
            transform: translateX(5px);
        }

        .data-source-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 8px;
        }

        .data-source-name {
            font-weight: 600;
            font-size: 14px;
            color: #1e293b;
        }

        .data-source-type {
            background: #e2e8f0;
            color: #64748b;
            padding: 2px 8px;
            border-radius: 12px;
            font-size: 11px;
            text-transform: uppercase;
        }

        .data-source-url {
            color: #3b82f6;
            font-size: 12px;
            margin-bottom: 8px;
            word-break: break-all;
            text-decoration: none;
        }

        .data-source-url:hover {
            text-decoration: underline;
        }

        .data-source-snippet {
            color: #64748b;
            font-size: 12px;
            line-height: 1.4;
            margin-bottom: 8px;
        }

        .data-source-meta {
            display: flex;
            gap: 10px;
            font-size: 11px;
            color: #94a3b8;
        }

        /* 系统状态统计 */
        .stats-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 15px;
            margin-top: 20px;
        }

        .stat-card {
            background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
            padding: 15px;
            border-radius: 12px;
            text-align: center;
            border: 1px solid #e2e8f0;
        }

        .stat-number {
            font-size: 24px;
            font-weight: bold;
            color: #4facfe;
            margin-bottom: 5px;
        }

        .stat-label {
            font-size: 12px;
            color: #64748b;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        /* 响应式设计 */
        @media (max-width: 1400px) {
            .main-container {
                grid-template-columns: 1fr 350px;
                min-width: 1000px;
            }
            
            .right-sidebar {
                min-width: 350px;
                max-width: 350px;
            }
        }

        @media (max-width: 1200px) {
            .main-container {
                grid-template-columns: 1fr 300px;
                min-width: 900px;
            }
            
            .right-sidebar {
                min-width: 300px;
                max-width: 300px;
            }
        }

        @media (max-width: 768px) {
            .main-container {
                grid-template-areas: 
                    "header"
                    "main";
                grid-template-columns: 1fr;
                grid-template-rows: 80px 1fr;
                min-width: 100%;
            }
            
            .right-sidebar {
                display: none;
            }
            
            .nav-menu {
                flex-wrap: wrap;
                gap: 15px;
            }
            
            .nav-item {
                font-size: 14px;
                padding: 10px 20px;
            }
        }

        /* 加载状态 */
        .loading {
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 40px;
            color: #64748b;
        }

        .spinner {
            width: 20px;
            height: 20px;
            border: 2px solid #e2e8f0;
            border-top: 2px solid #4facfe;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-right: 10px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        /* 空状态提示 */
        .empty-state {
            text-align: center;
            padding: 40px 20px;
            color: #94a3b8;
        }

        .empty-state-icon {
            font-size: 48px;
            margin-bottom: 15px;
            opacity: 0.5;
        }

        .empty-state-text {
            font-size: 16px;
            margin-bottom: 10px;
        }

        .empty-state-hint {
            font-size: 14px;
            opacity: 0.7;
        }

        /* 响应式调整 */
        @media (max-width: 1200px) {
            .config-grid {
                grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
                gap: 15px;
            }
        }

        @media (max-width: 768px) {
            .config-grid {
                grid-template-columns: 1fr;
                gap: 15px;
            }
            
            .config-actions {
                flex-direction: column;
                align-items: center;
            }
            
            .config-button {
                width: 100%;
                max-width: 200px;
            }
        }
    </style>
</head>
<body>
    <div class="main-container">
        <!-- 1. 顶部导航栏区域 - 系统功能模块切换 -->
        <header class="header">
            <div class="header-left">
                <div class="logo">🚀 MetasoCreator</div>
                <nav class="nav-menu">
                    <div class="nav-item active" onclick="switchMainView('search', this)">🔍 智能搜索</div>
                    <div class="nav-item" onclick="switchMainView('reader', this)">📖 内容读取</div>
                    <div class="nav-item" onclick="switchMainView('qa', this)">🤖 智能问答</div>
                    <div class="nav-item" onclick="switchMainView('analysis', this)">📊 数据分析</div>
                </nav>
            </div>
            <div class="header-right">
                <div class="status-indicator">
                    <div class="status-dot"></div>
                    <span>系统运行中</span>
                </div>
            </div>
        </header>

        <!-- 2. 左侧主应用区域 - 用户交互和内容展示 -->
        <main class="main-content">
            <!-- 2.1 参数配置区域 - 完全替换功能说明区域 -->
            <div class="parameter-config" id="parameterConfig">
                <!-- 智能搜索参数配置 -->
                <div id="searchConfig" class="config-section">
                    <div class="config-title">
                        <span>🔍 智能搜索</span>
                        <span>参数配置</span>
                    </div>
                    <div class="config-grid">
                        <div class="config-item">
                            <label for="searchScope" class="config-label">搜索范围</label>
                            <div class="custom-multiselect" id="searchScope-multiselect">
                                <div class="multiselect-input" id="searchScope-input">
                                    <div class="multiselect-tag">
                                        <span class="multiselect-tag-text">网页 (webpage)</span>
                                        <span class="multiselect-tag-remove" data-value="webpage">×</span>
                                    </div>
                                </div>
                                <div class="multiselect-arrow"></div>
                                <div class="multiselect-dropdown" id="searchScope-dropdown">
                                    <div class="multiselect-option selected" data-value="webpage">
                                        <div class="multiselect-option-checkbox"></div>
                                        <span>网页 (webpage)</span>
                                    </div>
                                    <div class="multiselect-option" data-value="document">
                                        <div class="multiselect-option-checkbox"></div>
                                        <span>文库 (document)</span>
                                    </div>
                                    <div class="multiselect-option" data-value="scholar">
                                        <div class="multiselect-option-checkbox"></div>
                                        <span>学术 (scholar)</span>
                                    </div>
                                    <div class="multiselect-option" data-value="podcast">
                                        <div class="multiselect-option-checkbox"></div>
                                        <span>播客 (podcast)</span>
                                    </div>
                                    <div class="multiselect-option" data-value="image">
                                        <div class="multiselect-option-checkbox"></div>
                                        <span>图片 (image)</span>
                                    </div>
                                    <div class="multiselect-option" data-value="video">
                                        <div class="multiselect-option-checkbox"></div>
                                        <span>视频 (video)</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="config-item">
                            <label for="searchSize" class="config-label">结果数量</label>
                            <select id="searchSize" class="config-select">
                                <option value="5">5个</option>
                                <option value="10">10个</option>
                                <option value="20">20个</option>
                                <option value="50">50个</option>
                                <option value="100">100个</option>
                            </select>
                        </div>
                        <div class="config-item">
                            <label for="searchIncludeSummary" class="config-label">包含摘要</label>
                            <div class="config-checkbox-group">
                                <div class="config-checkbox-item">
                                    <input type="checkbox" id="searchIncludeSummary">
                                    <label for="searchIncludeSummary">启用摘要匹配</label>
                                </div>
                            </div>
                        </div>
                        <div class="config-item">
                            <label class="config-label">搜索方式</label>
                            <div class="config-radio-group">
                                <div class="config-radio-item">
                                    <input type="radio" id="searchModePage" name="searchMode" value="page" checked>
                                    <label for="searchModePage">分页模式 (使用page参数)</label>
                                </div>
                                <div class="config-radio-item">
                                    <input type="radio" id="searchModeSize" name="searchMode" value="size">
                                    <label for="searchModeSize">数量模式 (使用size参数)</label>
                                </div>
                            </div>
                            <div style="font-size: 12px; color: #64748b; margin-top: 8px; line-height: 1.4;">
                                💡 <strong>分页模式</strong>：适合大量结果的分页浏览，使用page参数控制页码<br>
                                💡 <strong>数量模式</strong>：适合精确控制返回结果数量，使用size参数控制每页大小
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 智能问答参数配置 -->
                <div id="qaConfig" class="config-section hidden">
                    <div class="config-title">
                        <span>🤖 智能问答</span>
                        <span>参数配置</span>
                    </div>
                    <div class="config-grid">
                        <div class="config-item">
                            <label for="qaScope" class="config-label">搜索范围</label>
                            <div class="custom-multiselect" id="qaScope-multiselect">
                                <div class="multiselect-input" id="qaScope-input">
                                    <div class="multiselect-tag">
                                        <span class="multiselect-tag-text">网页 (webpage)</span>
                                        <span class="multiselect-tag-remove" data-value="webpage">×</span>
                                    </div>
                                </div>
                                <div class="multiselect-arrow"></div>
                                <div class="multiselect-dropdown" id="qaScope-dropdown">
                                    <div class="multiselect-option selected" data-value="webpage">
                                        <div class="multiselect-option-checkbox"></div>
                                        <span>网页 (webpage)</span>
                                    </div>
                                    <div class="multiselect-option" data-value="document">
                                        <div class="multiselect-option-checkbox"></div>
                                        <span>文库 (document)</span>
                                    </div>
                                    <div class="multiselect-option" data-value="scholar">
                                        <div class="multiselect-option-checkbox"></div>
                                        <span>学术 (scholar)</span>
                                    </div>
                                    <div class="multiselect-option" data-value="podcast">
                                        <div class="multiselect-option-checkbox"></div>
                                        <span>播客 (podcast)</span>
                                    </div>
                                    <div class="multiselect-option" data-value="image">
                                        <div class="multiselect-option-checkbox"></div>
                                        <span>图片 (image)</span>
                                    </div>
                                    <div class="multiselect-option" data-value="video">
                                        <div class="multiselect-option-checkbox"></div>
                                        <span>视频 (video)</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="config-item">
                            <label for="qaModel" class="config-label">AI模型</label>
                            <select id="qaModel" class="config-select">
                                <option value="">快速模型 (默认)</option>
                                <option value="fast_thinking">快速思考 (fast_thinking)</option>
                                <option value="ds-r1">深度思考 (ds-r1)</option>
                            </select>
                        </div>
                        <div class="config-item">
                            <label for="qaContext" class="config-label">对话上下文</label>
                            <div class="config-checkbox-group">
                                <div class="config-checkbox-item">
                                    <input type="checkbox" id="qaContext">
                                    <label for="qaContext">保持对话历史</label>
                                </div>
                            </div>
                        </div>
                        <div class="config-item">
                            <label class="config-label">响应模式</label>
                            <div class="config-radio-group">
                                <div class="config-radio-item">
                                    <input type="radio" id="qaResponseModeFast" name="qaResponseMode" value="fast" checked>
                                    <label for="qaResponseModeFast">快速响应</label>
                                </div>
                                <div class="config-radio-item">
                                    <input type="radio" id="qaResponseModeDetailed" name="qaResponseMode" value="detailed">
                                    <label for="qaResponseModeDetailed">详细回答</label>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 内容读取参数配置 -->
                <div id="readerConfig" class="config-section hidden">
                    <div class="config-title">
                        <span>📖 内容读取</span>
                        <span>参数配置</span>
                    </div>
                    <div class="config-grid">
                        <div class="config-item">
                            <label for="readerTimeout" class="config-label">超时时间</label>
                            <select id="readerTimeout" class="config-select">
                                <option value="15">15秒</option>
                                <option value="30">30秒</option>
                                <option value="60">60秒</option>
                            </select>
                        </div>
                        <div class="config-item">
                            <label for="readerFormat" class="config-label">输出格式</label>
                            <select id="readerFormat" class="config-select">
                                <option value="markdown">Markdown</option>
                                <option value="text">纯文本</option>
                                <option value="html">HTML</option>
                            </select>
                        </div>
                        <div class="config-item">
                            <label for="readerExtractImages" class="config-label">提取图片</label>
                            <div class="config-checkbox-group">
                                <div class="config-checkbox-item">
                                    <input type="checkbox" id="readerExtractImages">
                                    <label for="readerExtractImages">包含图片链接</label>
                                </div>
                            </div>
                        </div>
                        <div class="config-item">
                            <label class="config-label">读取模式</label>
                            <div class="config-radio-group">
                                <div class="config-radio-item">
                                    <input type="radio" id="readerModeFast" name="readerMode" value="fast" checked>
                                    <label for="readerModeFast">快速读取</label>
                                </div>
                                <div class="config-radio-item">
                                    <input type="radio" id="readerModeComplete" name="readerMode" value="complete">
                                    <label for="readerModeComplete">完整读取</label>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 数据分析参数配置 -->
                <div id="analysisConfig" class="config-section hidden">
                    <div class="config-title">
                        <span>📊 数据分析</span>
                        <span>参数配置</span>
                    </div>
                    <div class="config-grid">
                        <div class="config-item">
                            <label for="analysisType" class="config-label">分析类型</label>
                            <select id="analysisType" class="config-select">
                                <option value="general">通用分析</option>
                                <option value="sentiment">情感分析</option>
                                <option value="keyword">关键词提取</option>
                                <option value="summary">内容摘要</option>
                                <option value="classification">内容分类</option>
                            </select>
                        </div>
                        <div class="config-item">
                            <label for="analysisLanguage" class="config-label">分析语言</label>
                            <select id="analysisLanguage" class="config-select">
                                <option value="auto">自动检测</option>
                                <option value="zh">中文</option>
                                <option value="en">英文</option>
                                <option value="ja">日文</option>
                            </select>
                        </div>
                        <div class="config-item">
                            <label class="config-label">分析深度</label>
                            <div class="config-radio-group">
                                <div class="config-radio-item">
                                    <input type="radio" id="analysisDetailBasic" name="analysisDetail" value="basic" checked>
                                    <label for="analysisDetailBasic">基础</label>
                                </div>
                                <div class="config-radio-item">
                                    <input type="radio" id="analysisDetailAdvanced" name="analysisDetail" value="advanced">
                                    <label for="analysisDetailAdvanced">高级</label>
                                </div>
                            </div>
                        </div>
                        <div class="config-item">
                            <label class="config-label">输出格式</label>
                            <div class="config-radio-group">
                                <div class="config-radio-item">
                                    <input type="radio" id="analysisOutputText" name="analysisOutput" value="text" checked>
                                    <label for="analysisOutputText">文本</label>
                                </div>
                                <div class="config-radio-item">
                                    <input type="radio" id="analysisOutputJson" name="analysisOutput" value="json">
                                    <label for="analysisOutputJson">JSON</label>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 2.2 中间对话内容展示区域 -->
            <div class="chat-container" id="chatContainer">
                <div class="chat-message">
                    <div class="message-avatar assistant-avatar">🤖</div>
                    <div class="message-content">
                        <div class="message-header">
                            <span>MetasoCreator 助手</span>
                            <span>刚刚</span>
                        </div>
                        <div class="message-text">
                            欢迎使用智能搜索功能！请输入您要搜索的关键词，我将为您搜索相关信息并展示数据来源。
                        </div>
                    </div>
                </div>
            </div>

            <!-- 2.3 底部发送框区域 -->
            <div class="input-container">
                <div class="input-wrapper">
                    <textarea 
                        class="message-input" 
                        id="messageInput" 
                        placeholder="输入您要搜索的关键词..."
                        rows="1"
                        onkeypress="handleKeyPress(event)"
                    ></textarea>
                </div>
                <button class="send-button" onclick="sendMessage()" id="sendButton">
                    <span>搜索</span>
                    <span>🔍</span>
                </button>
                <button class="send-button" onclick="clearChat()" style="background: linear-gradient(135deg, #6c757d 0%, #495057 100%);">
                    <span>清空</span>
                    <span>🗑️</span>
                </button>
            </div>
        </main>

        <!-- 3. 右侧数据来源展示区域 - 展示系统检索到的实际数据来源 -->
        <aside class="right-sidebar">
            <div class="sidebar-section">
                <div class="sidebar-title">
                    📊 数据来源统计
                </div>
                <div class="stats-grid">
                    <div class="stat-card">
                        <div class="stat-number" id="searchCount">0</div>
                        <div class="stat-label">搜索次数</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-number" id="dataSourceCount">0</div>
                        <div class="stat-label">数据来源</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-number" id="totalResults">0</div>
                        <div class="stat-label">总结果数</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-number" id="apiStatus">🟢</div>
                        <div class="stat-label">API状态</div>
                    </div>
                </div>
            </div>

            <div class="sidebar-section">
                <div class="sidebar-title">
                    🔍 数据来源列表
                </div>
                <div id="dataSourceList">
                    <div class="empty-state">
                        <div class="empty-state-icon">🔍</div>
                        <div class="empty-state-text">暂无数据来源</div>
                        <div class="empty-state-hint">开始搜索后将显示数据来源</div>
                    </div>
                </div>
            </div>
        </aside>
    </div>

    <script>
        // 自定义多选下拉框类
        class CustomMultiSelect {
            constructor(elementId) {
                this.elementId = elementId;
                this.container = document.getElementById(elementId);
                this.input = this.container.querySelector('.multiselect-input');
                this.dropdown = this.container.querySelector('.multiselect-dropdown');
                this.options = this.container.querySelectorAll('.multiselect-option');
                this.selectedValues = [];
                
                this.init();
            }
            
            init() {
                // 初始化选中值
                this.selectedValues = ['webpage']; // 默认选中webpage
                this.updateDisplay();
                
                // 绑定事件
                this.input.addEventListener('click', () => this.toggleDropdown());
                this.dropdown.addEventListener('click', (e) => this.handleOptionClick(e));
                
                // 点击外部关闭下拉框
                document.addEventListener('click', (e) => {
                    if (!this.container.contains(e.target)) {
                        this.closeDropdown();
                    }
                });
                
                // 标签删除事件
                this.input.addEventListener('click', (e) => {
                    if (e.target.classList.contains('multiselect-tag-remove')) {
                        const value = e.target.getAttribute('data-value');
                        this.removeValue(value);
                        e.stopPropagation();
                    }
                });
            }
            
            toggleDropdown() {
                if (this.dropdown.classList.contains('show')) {
                    this.closeDropdown();
                } else {
                    this.openDropdown();
                }
            }
            
            openDropdown() {
                this.dropdown.classList.add('show');
                this.input.classList.add('focused');
            }
            
            closeDropdown() {
                this.dropdown.classList.remove('show');
                this.input.classList.remove('focused');
            }
            
            handleOptionClick(e) {
                const option = e.target.closest('.multiselect-option');
                if (!option) return;
                
                const value = option.getAttribute('data-value');
                if (this.selectedValues.includes(value)) {
                    this.removeValue(value);
                } else {
                    this.addValue(value);
                }
                
                e.stopPropagation();
            }
            
            addValue(value) {
                if (!this.selectedValues.includes(value)) {
                    this.selectedValues.push(value);
                    this.updateDisplay();
                }
            }
            
            removeValue(value) {
                const index = this.selectedValues.indexOf(value);
                if (index > -1) {
                    this.selectedValues.splice(index, 1);
                    this.updateDisplay();
                }
            }
            
            updateDisplay() {
                // 更新输入框显示
                this.input.innerHTML = '';
                
                if (this.selectedValues.length === 0) {
                    this.input.innerHTML = '<div class="multiselect-placeholder">请选择...</div>';
                } else {
                    this.selectedValues.forEach(value => {
                        const tag = document.createElement('div');
                        tag.className = 'multiselect-tag';
                        tag.innerHTML = `
                            <span class="multiselect-tag-text">${this.getValueDisplayName(value)}</span>
                            <span class="multiselect-tag-remove" data-value="${value}">×</span>
                        `;
                        this.input.appendChild(tag);
                    });
                }
                
                // 更新选项状态
                this.options.forEach(option => {
                    const value = option.getAttribute('data-value');
                    if (this.selectedValues.includes(value)) {
                        option.classList.add('selected');
                    } else {
                        option.classList.remove('selected');
                    }
                });
            }
            
            getValueDisplayName(value) {
                const displayNames = {
                    'webpage': '网页 (webpage)',
                    'document': '文库 (document)',
                    'scholar': '学术 (scholar)',
                    'podcast': '播客 (podcast)',
                    'image': '图片 (image)',
                    'video': '视频 (video)'
                };
                return displayNames[value] || value;
            }
            
            getSelectedValues() {
                return this.selectedValues;
            }
            
            setSelectedValues(values) {
                this.selectedValues = values || [];
                this.updateDisplay();
            }
        }

        // 全局变量
        let currentMainView = 'search';
        let chatHistory = [];
        let searchCount = 0;
        let dataSourceCount = 0;
        let totalResults = 0;
        let currentDataSources = [];
        let searchScopeMultiSelect = null;
        let qaScopeMultiSelect = null;
        
        // 常量定义
        const CONSTANTS = {
            INPUT_MAX_HEIGHT: 120,
            INIT_DELAY: 100,
            API_TEST_DELAY: 1000
        };

        // 初始化
        document.addEventListener('DOMContentLoaded', function() {
            initializeApp();
            
            // 在DOM加载完成后初始化多选组件
            setTimeout(() => {
                const searchElement = document.getElementById('searchScope-multiselect');
                const qaElement = document.getElementById('qaScope-multiselect');
                
                if (searchElement) {
                    searchScopeMultiSelect = new CustomMultiSelect('searchScope-multiselect');
                }
                if (qaElement) {
                    qaScopeMultiSelect = new CustomMultiSelect('qaScope-multiselect');
                }
            }, CONSTANTS.INIT_DELAY);
        });

        function initializeApp() {
            // 设置输入框自动调整高度
            const messageInput = document.getElementById('messageInput');
            messageInput.addEventListener('input', function() {
                this.style.height = 'auto';
                this.style.height = Math.min(this.scrollHeight, 120) + 'px';
            });
            
            // 添加键盘事件监听器
            messageInput.addEventListener('keypress', handleKeyPress);

            // 更新统计信息
            updateStats();
            
            // 初始化显示搜索配置
            showConfigSection('search');
            
            // 测试API连接
            testAPI().then(connected => {
                if (connected) {
                    // 如果API连接正常，测试搜索API
                    setTimeout(() => {
                        testSearchAPI();
                    }, 1000);
                }
            });
            
            // 添加布局调试信息
            console.log('布局信息:', {
                containerWidth: document.querySelector('.main-container').offsetWidth,
                mainContentWidth: document.querySelector('.main-content').offsetWidth,
                rightSidebarWidth: document.querySelector('.right-sidebar').offsetWidth,
                windowWidth: window.innerWidth
            });
            
            // 监听窗口大小变化
            window.addEventListener('resize', () => {
                console.log('窗口大小变化:', {
                    containerWidth: document.querySelector('.main-container').offsetWidth,
                    mainContentWidth: document.querySelector('.main-content').offsetWidth,
                    rightSidebarWidth: document.querySelector('.right-sidebar').offsetWidth,
                    windowWidth: window.innerWidth
                });
            });
        }

        // 更新功能说明
        function updateFunctionInfo(view) {
            const messageInput = document.getElementById('messageInput');
            const sendButton = document.getElementById('sendButton');
            
            switch(view) {
                case 'search':
                    messageInput.placeholder = "输入您要搜索的关键词...";
                    sendButton.innerHTML = '<span>搜索</span><span>🔍</span>';
                    break;
                case 'reader':
                    messageInput.placeholder = "输入要读取的网页URL...";
                    sendButton.innerHTML = '<span>读取</span><span>📖</span>';
                    break;
                case 'qa':
                    messageInput.placeholder = "输入您的问题...";
                    sendButton.innerHTML = '<span>提问</span><span>🤖</span>';
                    break;
                case 'analysis':
                    messageInput.placeholder = "输入要分析的内容...";
                    sendButton.innerHTML = '<span>分析</span><span>📊</span>';
                    break;
            }
        }
        
        // 获取视图显示名称的辅助函数
        function getViewDisplayName(view) {
            const viewNames = {
                'search': '智能搜索',
                'qa': '智能问答',
                'reader': '内容读取',
                'analysis': '数据分析'
            };
            return viewNames[view] || view;
        }

        // 切换主视图
        function switchMainView(view, targetElement) {
            currentMainView = view;
            
            // 更新导航菜单状态
            document.querySelectorAll('.nav-item').forEach(item => {
                item.classList.remove('active');
            });
            
            // 如果传入了目标元素，则添加active类
            if (targetElement) {
                targetElement.classList.add('active');
            } else {
                // 兜底方案：根据view查找对应元素
                const navItems = document.querySelectorAll('.nav-item');
                navItems.forEach(item => {
                    if (item.textContent.includes(getViewDisplayName(view))) {
                        item.classList.add('active');
                    }
                });
            }

            // 更新功能说明
            updateFunctionInfo(view);
            
            // 清空聊天容器
            clearChat();
            
            // 清空数据来源
            clearDataSources();
            
            // 重置统计信息
            dataSourceCount = 0;
            totalResults = 0;
            updateStats();

            // 显示对应的参数配置
            showConfigSection(view);
        }

        // 发送消息
        function sendMessage() {
            const messageInput = document.getElementById('messageInput');
            const message = messageInput.value.trim();
            
            if (!message) return;

            // 添加用户消息
            addMessage('user', message);
            
            // 清空输入框
            messageInput.value = '';
            messageInput.style.height = 'auto';

            // 根据当前功能处理消息
            switch(currentMainView) {
                case 'search':
                    performSearchWithConfig(message);
                    break;
                case 'reader':
                    performReaderWithConfig(message);
                    break;
                case 'qa':
                    performQAWithConfig(message);
                    break;
                case 'analysis':
                    performAnalysisWithConfig(message);
                    break;
                default:
                    performSearchWithConfig(message);
            }
        }

        // 使用配置参数执行搜索
        async function performSearchWithConfig(query) {
            const searchScope = searchScopeMultiSelect ? searchScopeMultiSelect.getSelectedValues() : ['webpage'];
            const searchSize = document.getElementById('searchSize').value;
            const searchIncludeSummary = document.getElementById('searchIncludeSummary').checked;
            const searchMode = document.querySelector('input[name="searchMode"]:checked').value;

            const loadingId = addMessage('assistant', '<div class="loading"><div class="spinner"></div>正在处理您的请求...</div>');

            try {
                // 构建请求参数
                const requestBody = {
                    q: query,
                    scope: searchScope.join(','),
                    includeSummary: searchIncludeSummary
                };

                // 根据搜索模式添加相应参数，确保page和size不会同时存在
                if (searchMode === 'page') {
                    // 分页模式：使用page参数，不包含size参数
                    requestBody.page = 1; // 默认第一页
                } else {
                    // 数量模式：使用size参数，不包含page参数
                    requestBody.size = parseInt(searchSize);
                }

                console.log('搜索请求参数:', requestBody); // 调试日志

                const response = await fetch('/api/search/', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(requestBody)
                });

                if (!response.ok) {
                    const errorData = await response.json();
                    throw new Error(`HTTP ${response.status}: ${errorData.error || errorData.message || '未知错误'}`);
                }

                const data = await response.json();
                searchCount++;
                totalResults = data.total_results || 0;

                if (data.success) {
                    const results = data.results || [];
                    // 更新数据来源列表
                    updateDataSources(results);
                    // 更新数据来源统计
                    dataSourceCount = results.length;
                    
                    let result = `🔍 搜索 "${query}" 的结果：\n\n`;
                    result += `📊 共找到 ${data.total_results} 个结果\n\n`;
                    
                    results.forEach((item, index) => {
                        result += `**${index + 1}. ${item.title}**\n`;
                        result += `🔗 ${item.url}\n`;
                        result += `📝 ${item.snippet}\n`;
                        if (item.source) result += `🏷️ 来源：${item.source}\n`;
                        result += '\n';
                    });

                    updateMessage(loadingId, 'assistant', result);
                } else {
                    updateMessage(loadingId, 'assistant', `❌ 搜索失败：${data.error}`);
                    // 搜索失败时清空数据来源
                    clearDataSources();
                    dataSourceCount = 0;
                }
                updateStats();
            } catch (error) {
                console.error('搜索错误:', error); // 调试日志
                updateMessage(loadingId, 'assistant', `抱歉，处理您的请求时出现了错误：${error.message}`);
            }
        }

        // 使用配置参数执行智能问答
        async function performQAWithConfig(question) {
            const qaScope = qaScopeMultiSelect ? qaScopeMultiSelect.getSelectedValues() : ['webpage'];
            const qaModel = document.getElementById('qaModel').value;
            const qaContext = document.getElementById('qaContext').checked;
            const qaResponseMode = document.querySelector('input[name="qaResponseMode"]:checked').value;

            const loadingId = addMessage('assistant', '<div class="loading"><div class="spinner"></div>正在处理您的请求...</div>');

            try {
                // 构建请求参数
                const requestBody = {
                    messages: [
                        {
                            role: 'user',
                            content: question
                        }
                    ],
                    scope: qaScope.join(','),
                    context: qaContext,
                    response_mode: qaResponseMode
                };

                // 只有当选择了特定模型时才添加model参数
                if (qaModel && qaModel.trim() !== '') {
                    requestBody.model = qaModel;
                }

                console.log('智能问答请求参数:', requestBody); // 调试日志

                const response = await fetch('/api/chat/completions', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(requestBody)
                });

                if (!response.ok) {
                    const errorData = await response.json();
                    throw new Error(`HTTP ${response.status}: ${errorData.error || errorData.message || '未知错误'}`);
                }

                const data = await response.json();

                if (data.choices && data.choices.length > 0) {
                    let result = `🤖 智能问答结果：\n\n`;
                    result += `💬 问题：${question}\n\n`;
                    result += `💬 回答：${data.choices[0].message.content}\n\n`;
                    
                    // 检查citations字段（正确的数据来源字段）
                    const citations = data.choices[0].message.citations;
                    if (citations && citations.length > 0) {
                        updateDataSources(citations);
                        // 更新数据来源统计
                        dataSourceCount = citations.length;
                        result += `📚 参考来源：\n`;
                        citations.forEach((citation, index) => {
                            result += `${index + 1}. ${citation.title || citation.link}\n`;
                        });
                    } else {
                        // 如果没有citations，清空数据来源
                        clearDataSources();
                        dataSourceCount = 0;
                    }
                    
                    updateMessage(loadingId, 'assistant', result);
                } else {
                    updateMessage(loadingId, 'assistant', `❌ 问答失败：${data.error || '未知错误'}`);
                }
                updateStats();
            } catch (error) {
                console.error('问答错误:', error);
                updateMessage(loadingId, 'assistant', `抱歉，处理您的请求时出现了错误：${error.message}`);
            }
        }
        
        // 使用配置参数执行内容读取
        async function performReaderWithConfig(url) {
            const loadingId = addMessage('assistant', '<div class="loading"><div class="spinner"></div>正在读取内容...</div>');
            
            try {
                addMessage('assistant', `📖 内容读取功能暂未实现，URL: ${url}`);
                updateMessage(loadingId, 'assistant', '内容读取功能正在开发中...');
            } catch (error) {
                console.error('读取错误:', error);
                updateMessage(loadingId, 'assistant', `读取内容时出现错误：${error.message}`);
            }
        }
        
        // 使用配置参数执行数据分析
        async function performAnalysisWithConfig(content) {
            const loadingId = addMessage('assistant', '<div class="loading"><div class="spinner"></div>正在分析数据...</div>');
            
            try {
                addMessage('assistant', `📊 数据分析功能暂未实现，内容: ${content}`);
                updateMessage(loadingId, 'assistant', '数据分析功能正在开发中...');
            } catch (error) {
                console.error('分析错误:', error);
                updateMessage(loadingId, 'assistant', `分析数据时出现错误：${error.message}`);
            }
        }
        
        // 添加消息到聊天
        function addMessage(role, content) {
            const chatContainer = document.getElementById('chatContainer');
            if (!chatContainer) {
                console.error('Chat container not found');
                return null;
            }
            
            const messageId = 'msg_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
            const messageDiv = document.createElement('div');
            messageDiv.className = `chat-message ${role}-message`;
            messageDiv.id = messageId;
            
            const avatar = role === 'user' ? '👤' : '🤖';
            const avatarClass = role === 'user' ? 'user-avatar' : 'assistant-avatar';
            const name = role === 'user' ? '用户' : 'MetasoCreator 助手';
            
            messageDiv.innerHTML = `
                <div class="message-avatar ${avatarClass}">${avatar}</div>
                <div class="message-content">
                    <div class="message-header">
                        <span>${name}</span>
                        <span>刚刚</span>
                    </div>
                    <div class="message-text">
                        ${content}
                    </div>
                </div>
            `;
            
            chatContainer.appendChild(messageDiv);
            chatContainer.scrollTop = chatContainer.scrollHeight;
            
            return messageId;
        }
        
        // 更新消息内容
        function updateMessage(messageId, role, content) {
            const messageElement = document.getElementById(messageId);
            if (messageElement) {
                const avatar = role === 'user' ? '👤' : '🤖';
                const avatarClass = role === 'user' ? 'user-avatar' : 'assistant-avatar';
                const name = role === 'user' ? '用户' : 'MetasoCreator 助手';
                
                messageElement.className = `chat-message ${role}-message`;
                messageElement.innerHTML = `
                    <div class="message-avatar ${avatarClass}">${avatar}</div>
                    <div class="message-content">
                        <div class="message-header">
                            <span>${name}</span>
                            <span>刚刚</span>
                        </div>
                        <div class="message-text">
                            ${content}
                        </div>
                    </div>
                `;
            }
        }
        
        // 清空聊天
        function clearChat() {
            const chatContainer = document.getElementById('chatContainer');
            if (chatContainer) {
                chatContainer.innerHTML = '';
                
                // 添加欢迎消息
                const welcomeMessage = `
                    <div class="chat-message">
                        <div class="message-avatar assistant-avatar">🤖</div>
                        <div class="message-content">
                            <div class="message-header">
                                <span>MetasoCreator 助手</span>
                                <span>刚刚</span>
                            </div>
                            <div class="message-text">
                                欢迎使用${getViewDisplayName(currentMainView)}功能！请输入您要${currentMainView === 'search' ? '搜索的关键词' : currentMainView === 'reader' ? '读取的网页URL' : currentMainView === 'qa' ? '的问题' : '分析的内容'}，我将为您提供帮助。
                            </div>
                        </div>
                    </div>
                `;
                chatContainer.innerHTML = welcomeMessage;
            }
            chatHistory = [];
        }
        
        // 更新统计信息
        function updateStats() {
            const searchCountElement = document.getElementById('searchCount');
            const dataSourceCountElement = document.getElementById('dataSourceCount');
            const totalResultsElement = document.getElementById('totalResults');
            
            if (searchCountElement) searchCountElement.textContent = searchCount;
            if (dataSourceCountElement) dataSourceCountElement.textContent = dataSourceCount;
            if (totalResultsElement) totalResultsElement.textContent = totalResults;
        }
        
        // 更新数据来源
        function updateDataSources(sources) {
            currentDataSources = sources || [];
            const dataSourceList = document.getElementById('dataSourceList');
            
            if (!dataSourceList) return;
            
            if (currentDataSources.length === 0) {
                dataSourceList.innerHTML = '<div class="empty-state"><div class="empty-state-icon">🔍</div><div class="empty-state-text">暂无数据来源</div><div class="empty-state-hint">开始搜索后将显示数据来源</div></div>';
                return;
            }
            
            dataSourceList.innerHTML = currentDataSources.map((source, index) => `
                <div class="data-source-item">
                    <div class="data-source-header">
                        <div class="data-source-name">${source.title || '未知标题'}</div>
                        <div class="data-source-type">${source.authors ? source.authors.join(', ') : 'web'}</div>
                    </div>
                    <a href="${source.link || source.url || '#'}" class="data-source-url" target="_blank">${source.link || source.url || ''}</a>
                    <div class="data-source-snippet">${source.snippet || source.summary || source.content || ''}</div>
                    <div class="data-source-meta">
                        <span>日期: ${source.date || 'N/A'}</span>
                        <span>作者: ${source.authors ? source.authors.join(', ') : 'N/A'}</span>
                    </div>
                </div>
            `).join('');
        }
        
        // 清空数据来源
        function clearDataSources() {
            currentDataSources = [];
            const dataSourceList = document.getElementById('dataSourceList');
            if (dataSourceList) {
                dataSourceList.innerHTML = '<div class="empty-state"><div class="empty-state-icon">🔍</div><div class="empty-state-text">暂无数据来源</div><div class="empty-state-hint">开始搜索后将显示数据来源</div></div>';
            }
        }
        
        // 显示配置区域
        function showConfigSection(view) {
            // 隐藏所有配置区域
            const configSections = document.querySelectorAll('.config-section');
            configSections.forEach(section => {
                section.style.display = 'none';
            });
            
            // 显示对应的配置区域
            const targetSection = document.getElementById(`${view}Config`);
            if (targetSection) {
                targetSection.style.display = 'block';
            }
        }
        
        // 清空搜索配置
        function clearSearchConfig() {
            if (searchScopeMultiSelect) {
                searchScopeMultiSelect.setSelectedValues(['webpage']);
            }
            
            const searchSize = document.getElementById('searchSize');
            const searchIncludeSummary = document.getElementById('searchIncludeSummary');
            const searchModeSize = document.getElementById('searchModeSize');
            
            if (searchSize) searchSize.value = '10';
            if (searchIncludeSummary) searchIncludeSummary.checked = true;
            if (searchModeSize) searchModeSize.checked = true;
        }
        
        // 清空问答配置
        function clearQAConfig() {
            if (qaScopeMultiSelect) {
                qaScopeMultiSelect.setSelectedValues(['webpage']);
            }
            
            const qaModel = document.getElementById('qaModel');
            const qaContext = document.getElementById('qaContext');
            const qaResponseModeStream = document.getElementById('qaResponseModeStream');
            
            if (qaModel) qaModel.value = '';
            if (qaContext) qaContext.checked = true;
            if (qaResponseModeStream) qaResponseModeStream.checked = true;
        }
        
        // 测试API连接
        async function testAPI() {
            try {
                const response = await fetch('/api/test');
                const data = await response.json();
                return data.success || false;
            } catch (error) {
                console.error('API测试失败:', error);
                return false;
            }
        }
        
        // 测试搜索API
        async function testSearchAPI() {
            try {
                const response = await fetch('/api/search/test');
                const data = await response.json();
                console.log('搜索API测试结果:', data);
            } catch (error) {
                console.error('搜索API测试失败:', error);
            }
        }
        
        // 键盘事件处理
        function handleKeyPress(event) {
            if (event.key === 'Enter' && !event.shiftKey) {
                event.preventDefault();
                sendMessage();
            }
        }
        
        // 全局错误处理
        window.addEventListener('error', function(event) {
            console.error('全局错误:', event.error);
        });
        
        window.addEventListener('unhandledrejection', function(event) {
            console.error('未处理的Promise拒绝:', event.reason);
        });
        
    </script>
</body>
</html>